//
//  SettingViewController.swift
//  FeastBooking
//
//  Created by Imon on 2017/12/5.
//  Copyright © 2017年 Imon. All rights reserved.
//

import UIKit

class SettingViewController: UIViewController {

    var logoutCompletion: (() -> Void)?
    
    let authManager = AuthManager.share
    
    let version: SettingBar = {
        let menu = SettingBar()
        menu.titleLabel.text = LanguageHelper.getString(key: "VERSION_UPDATE")
        menu.valueLabel.text = "v\(APPVERSION)"
        return menu
    }()
    
    let clearCache: SettingBar = {
        let menu = SettingBar()
        menu.titleLabel.text = LanguageHelper.getString(key: "CLEAR_CACHE")
        menu.valueLabel.text = ""
        return menu
    }()
    
    let agreement: SettingBar = {
        let menu = SettingBar()
        menu.titleLabel.text = LanguageHelper.getString(key: "SERVICE_AGREEMENT")
        menu.valueLabel.text = ""
        return menu
    }()
    
    var scrollView: UIScrollView?
    
    var actionSheet: UIAlertController!
    
    var visualView: UIVisualEffectView?
    
    fileprivate let activityView: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        view.startAnimating()
        return view
    }()
    
    let statusMessage: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.white
        label.textAlignment = .left
        label.font = AppFont(size: 17)
        label.text = LanguageHelper.getString(key: "CLEAR_SUCCESS")
        return label
    }()
    
    @IBOutlet weak var logoutButton: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = lightSaperatorColor
        self.navigationItem.title = LanguageHelper.getString(key: "SETTING")
        setBackBarItem()
        
        scrollView = UIScrollView()
        scrollView?.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height - logoutButton.frame.height)
        scrollView?.showsVerticalScrollIndicator = false
        scrollView?.showsHorizontalScrollIndicator = false
        scrollView?.isScrollEnabled = true
        scrollView?.alwaysBounceVertical = true
        scrollView?.autoresizingMask = UIViewAutoresizing.flexibleHeight
        
        version.frame = CGRect(x: 0, y: 0 , width: self.view.bounds.width, height: menuHeight)
        clearCache.frame = CGRect(x: 0, y: menuHeight , width: self.view.bounds.width, height: menuHeight)
        agreement.frame = CGRect(x: 0, y: menuHeight * 2 , width: self.view.bounds.width, height: menuHeight)
        scrollView?.addSubview(version)
        scrollView?.addSubview(clearCache)
        scrollView?.addSubview(agreement)
        self.view.addSubview(scrollView!)
        
        setCacheSize()
        setActionSheet()
        setVisualView()
        
        logoutButton.backgroundColor = UIColor.white
        logoutButton.addTarget(self, action: #selector(logout(_:)), for: .touchUpInside)
        
        let ccTapGR = UITapGestureRecognizer()
        ccTapGR.addTarget(self, action: #selector(tapClearCache(_:)))
        clearCache.addGestureRecognizer(ccTapGR)
        
        let verTapGR = UITapGestureRecognizer()
        verTapGR.addTarget(self, action: #selector(tapVersion(_:)))
        version.addGestureRecognizer(verTapGR)
        
        let agreeTapGR = UITapGestureRecognizer()
        agreeTapGR.addTarget(self, action: #selector(tapAgreement(_:)))
        agreement.addGestureRecognizer(agreeTapGR)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if LATESTVERSION > APPVERSION {
            version.showRedPoint()
        } else {
            version.hideRedPoint()
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func setVisualView() {
        let visualSize: CGFloat = 100
        let effect = UIBlurEffect(style: .dark)
        visualView = UIVisualEffectView(effect: effect)
        visualView?.frame = CGRect(x: (view.bounds.width - visualSize) / 2, y: (view.bounds.height - visualSize) / 2 - 64, width: visualSize, height: visualSize)
        visualView?.layer.cornerRadius = 8
        visualView?.layer.masksToBounds = true
        
        activityView.center = CGPoint(x: visualView!.frame.width/2.0, y: visualView!.frame.height/2.0)
        activityView.color = UIColor.white
        let maxSize = CGSize(width: self.view.bounds.width, height: 40)
        let messageSize = TextSize.textSize(text: statusMessage.text!, font: statusMessage.font, maxSize: maxSize)
        statusMessage.frame = CGRect(x: (visualSize - messageSize.width) / 2, y: (visualSize - messageSize.height) / 2, width: messageSize.width, height: messageSize.height)
        visualView?.contentView.addSubview(activityView)
        visualView?.contentView.addSubview(statusMessage)
    }
    
    func tapClearCache(_ sender: UITapGestureRecognizer) {
        UIView.animate(withDuration: 0.3, animations: { [unowned self] in
            self.clearCache.backgroundColor = UIColor.init(red: 200 / 255.0, green: 200 / 255.0, blue: 200 / 255.0, alpha: 0.5)
            }, completion: { [unowned self] bool in
                self.clearCache.backgroundColor = UIColor.white
                self.present(self.actionSheet, animated: true, completion: nil)
        })
    }
    
    func tapAgreement(_ sender: UITapGestureRecognizer) {
        UIView.animate(withDuration: 0.3, animations: { [unowned self] in
            self.agreement.backgroundColor = UIColor.init(red: 200 / 255.0, green: 200 / 255.0, blue: 200 / 255.0, alpha: 0.5)
            }, completion: { [unowned self] bool in
                self.agreement.backgroundColor = UIColor.white
                let agreementPage = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "AgreementNavigationController") as! UINavigationController
                self.present(agreementPage, animated: true, completion: nil)
        })
    }
    
    func setActionSheet() {
        actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        actionSheet.addAction(UIAlertAction(title: LanguageHelper.getString(key: "CANCEL"), style: .cancel, handler: { _ in
            
        }))
        actionSheet.addAction(UIAlertAction(title: LanguageHelper.getString(key: "SUER_CLEAR"), style: .default, handler: { [unowned self] _ in
            self.clear()
        }))
    }
    
    func showClearingView() {
        statusMessage.alpha = 0
        activityView.startAnimating()
        self.view.addSubview(visualView!)
    }
    
    func removeClearingView() {
        activityView.stopAnimating()
        statusMessage.alpha = 1
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            self.visualView?.removeFromSuperview()
        }
    }
    
    func setCacheSize() {
        let cacheSize = fileSizeOfCache()
        clearCache.valueLabel.text = "\(cacheSize)M"
    }
    
    func fileSizeOfCache()-> Int {
        
        // 取出cache文件夹目录 缓存文件都在这个目录下
        let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
        //缓存目录路径
        
        // 取出文件夹下所有文件数组
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        
        //快速枚举出所有文件名 计算文件大小
        var size = 0
        for file in fileArr! {
            // 把文件名拼接到路径中
            if let cP = cachePath {
                let path = cP + "/\(file)"
                // 取出文件属性
                let floder = try! FileManager.default.attributesOfItem(atPath: path)
                // 用元组取出文件大小属性
                for (abc, bcd) in floder {
                    // 累加文件大小
                    if abc == FileAttributeKey.size {
                        size += (bcd as AnyObject).integerValue
                    }
                }
            }
        }
        
        let mm = size / 1024 / 1024
        
        return mm
    }
    
    func logout(_ sender: UIButton) {
        let al = UIAlertController.init(title: nil, message: LanguageHelper.getString(key: "SURE_LOGOUT"), preferredStyle: .alert)
        let confirm = UIAlertAction.init(title: LanguageHelper.getString(key: "OK"), style: .destructive, handler: { [unowned self] _ in
            self.logoutIM() //先登出IM服務器
            self.authManager.logout()
            SystemMessageDB.logoutInstance() //退出当前用户系统消息的数据库
            RecentSearchDB.logoutInstance()  //退出当前用户最近搜索的数据库
            if let completion = self.logoutCompletion {
                completion()
            }
            self.navigationController?.popViewController(animated: true)
        })
        let cancel = UIAlertAction.init(title: LanguageHelper.getString(key: "CANCEL"), style: .cancel, handler: nil)
        al.addAction(confirm)
        al.addAction(cancel)
        self.present(al, animated: true, completion: nil)
    }
    
    func logoutIM() {
        JMSGUser.logout({ (result, error) in
            JCVerificationInfoDB.shareInstance.queue = nil
            UserDefaults.standard.removeObject(forKey: kCurrentUserName)
            UserDefaults.standard.removeObject(forKey: kCurrentUserPassword)
        })
    }
    
    func clear() {
        showClearingView()
        // 取出cache文件夹目录 缓存文件都在这个目录下
        let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
        
        // 取出文件夹下所有文件数组
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        
        // 遍历删除
        for file in fileArr! {
            if let cP = cachePath {
            let path = cP + "/\(file)"
                if FileManager.default.fileExists(atPath: path) {
                    do {
                        try FileManager.default.removeItem(atPath: path)
                    } catch {
                    
                    }
                }
            }
        }
        
        setCacheSize()
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            self.removeClearingView()
        }
    }
    
    func tapVersion(_ sender: UITapGestureRecognizer) {
        if LATESTVERSION > APPVERSION {
            let alertController = UIAlertController(title: "\(LanguageHelper.getString(key: "NEW_VERSION")) (v\(LATESTVERSION))",
                                                message: nil, preferredStyle: .alert)
            let okAction = UIAlertAction(title: LanguageHelper.getString(key: "YES"), style: .cancel, handler: {
                action in
                self.gotoAppStore()
            })
            let cancelAction = UIAlertAction(title: LanguageHelper.getString(key: "NOT_NOW"), style: .default,
                                        handler: nil)
            alertController.addAction(cancelAction)
            alertController.addAction(okAction)
            self.present(alertController, animated: true, completion: nil)
        } else {
            self.showPromptView(message: LanguageHelper.getString(key: "UP_TO_DATE"), confirmText: LanguageHelper.getString(key: "OK"))
        }
    }
    
    func gotoAppStore() {
        let urlString = "http://fir.im/w2a5"
        let url = URL(string: urlString)
        UIApplication.shared.open(url!, options: [:], completionHandler: nil)
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
}
